<template>
  <div class="box-content">
    <Navbar
      :appTitle="title"
      rtitle="..."
      :rname="rname"
      :actions="navActions"
      @clickAction="clickAction"
    />
    <Search
      ref="topSearch"
      class="search"
      placeholder="工单编号|生产物料|工序名称|批次编号"
      :isAdd="false"
      :isScreen="true"
      :isType="true"
      @onSearch="onSearch"
      @onScreen="onScreen"
    >
      <div v-if="GLOBAL.currentEnvironment" @click="clickAction('批量处理')" slot='rightText' style="margin-left:0.1rem">批量处理</div>
    </Search>
    <van-dropdown-menu active-color="#1989fa">
      <!-- <van-dropdown-item title="处理状态" ref="item">
        <van-cell title="全选">
          <template #right-icon>
            <van-checkbox name="all" @click="toggleAll" v-model="checkedAll" />
          </template>
        </van-cell>
        <van-checkbox-group v-model="selectedList" ref="checkboxGroup">
          <van-cell-group>
            <van-cell
              center
              :title="item.text"
              v-for="(item, index) in options1"
              :key="item.value"
              @click="toggle(index)"
            >
              <template #right-icon>
                <van-checkbox
                  :name="item.value"
                  ref="checkboxes"
                ></van-checkbox>
              </template>
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
        <div class="search-bottom">
          <span class="btncancel" @click="cancelType">重置</span>
          <span class="btnconfirm" @click="comfirmType">确定</span>
        </div>
      </van-dropdown-item> -->
      <van-dropdown-checkbox
        title="处理状态"
        :columns="options1"
        :selectValue="selectedList"
        @comfirm="comfirmType"
      ></van-dropdown-checkbox>
      <van-dropdown-item
        title="提交时间"
        @open="createdTimeBeginVisible = true"
      />
    </van-dropdown-menu>
    <search-tag
      ref="SearchTag"
      :propsForSon="propsForSon"
      @resetCategory="resetCategory"
      @getCategory="getCategory"
      v-show="showSearchTag"
    ></search-tag>

    <!--分页列表 -->
    <div class="listBox" :style="{height: GLOBAL.currentEnvironment ? 'calc(100vh - 1rem)' : 'calc(100vh - 1.5rem)'}">
      <pageList
        ref="pageList"
        :checkedShow="checkedShow"
        :operationTxt="operationTxt"
        :columns="columns"
        :listUrl="listUrl"
        @getCheckedValue="getCheckedValue"
        @handleList="handleList"
        :minLen="3"
      >
        <div slot="label" slot-scope="{ item }">
          <div class="label">
            <span
              v-for="(i, j) in columns.labelKey"
              :key="j"
              :style="{ color: setColor(i, item) }"
              >{{
                `${columns.labelText ? columns.labelText[i] : ""}${
                  i == "alreadyHandleNum"
                    ? item[i] + item["reportWorkUnitText"]
                    : item[i]
                }`
              }}</span
            >
          </div>
        </div>
        <div
          v-show="showAction(item)"
          slot="foot"
          slot-scope="{ item }"
          @click.stop="actions(item)"
          class="foot-slot"
        >
          <span></span>处理
        </div>
      </pageList>
    </div>
    <!--提交开始时间 -->
    <van-popup v-model="createdTimeBeginVisible" position="bottom">
      <van-datetime-picker
        @confirm="confirmCreatedStartTime"
        @cancel="cancelCreatedStartTime"
        type="date"
        title="提交开始时间"
        v-model="minDate"
      />
    </van-popup>
    <!--提交结束时间 -->
    <van-popup v-model="createdTimeEndVisible" position="bottom">
      <van-datetime-picker
        @confirm="confirmCreatedEndTime"
        @cancel="cancelCreatedEndTime"
        type="date"
        title="提交结束时间"
        :min-date="createEndMinDate"
      />
    </van-popup>
  </div>
</template>

<script>
import Search from "@/components/search";
import SearchTag from "./SearchTag";
import Navbar from "@/components/navBar/navBar_right";
import TabBar from "@/components/TabBar";
import pageList from "@/components/pageList";
import moment from "moment";
import { getAction } from "@/api/manage";
import VanDropdownCheckbox from "@/views/workManagement/defectsDeal/VanDropdownCheckbox";
export default {
  name: "carRoomList",
  components: { Navbar, TabBar, pageList, Search, SearchTag, VanDropdownCheckbox },
  data() {
    return {
      navActions: [{ text: "批量处理" }],
      title: "不合格品待处理",
      rname: "", //search
      active: "0",
      checkedShow: false, //列表是否支持选择
      operationTxt: "", //选择按钮名称
      listUrl: "mess/messNotQualityHandleIinfo/list", //列表接口
      columns: {
        titleKey: "orderCode", //标题
        subtitleKey: "processName", //副标题
        content: [
          //内容
          {
            name: "物料名称",
            key: ["goodsName"],
          },
          {
            name: "不合格品数量",
            key: ["notQualityNum", "reportWorkUnitText"],
          },
          {
            name: "展示批次",
            key: ["batchCode", "batchId"],
          },
        ],
        labelKey: ["handleStatusText", "alreadyHandleNum"], //标签
        labelText: { handleStatusText: "", alreadyHandleNum: "已处理：" }, //标签
        dynamicChecked: true,
        canCheckedNum: 0
      },
      showSearchTag: false,
      keyword: "",
      params: {
        handleStatus: "notStart,handling",
      },
      selectedList: ["notStart", "handling"],
      options1: [
        { text: "未开始", value: "notStart" },
        { text: "正在处理", value: "handling" },
        { text: "处理完成", value: "finish" },
      ],
      propsForSon: {},
      createdTimeBeginVisible: false,
      createdTimeEndVisible: false,
      minDate: new Date(),
      createEndMinDate: new Date(2020, 1, 1),
      checkedAll: false,
      notLeave: true,
    };
  },
  // 路由返回时先判断当前页是否存在弹窗，有就先关闭弹窗不返回，直到所有弹窗关闭再返回
  beforeRouteLeave(to, from, next) {
    let that = this;
    switch (true) {
      // that.showSearchTag是当前页的筛选弹窗，that.$refs.SearchTag.ddthrVisible是子组件筛选弹窗内的其他弹窗例如人员选择
      case that.showSearchTag && !that.$refs.SearchTag.ddthrVisible:
        that.showSearchTag = false;
        this.title = "不合格品待处理";
        next(false);
        break;
      case that.$refs.SearchTag.ddthrVisible:
        that.$refs.SearchTag.ddthrVisible = false;
        this.title = "更多筛选";
        next(false);
        break;
      case that.checkedShow && !that.showSearchTag && that.notLeave:
        that.checkedShow = false
        next(false);
        break;
      case !that.showSearchTag:
        next();
        break;
    }
  },
  mounted() {
    this.searchQuery();
  },
  created() {
    getAction('mess/messNotQualityHandleIinfo/list', { handleStatus: "notStart,handling" }).then(res => {
      this.columns.canCheckedNum = res.result.total
    })
  },
  methods: {
    // 动态禁用复选框
    canNotCheck(item) {
      if (item.handleStatus == 'finish') {
        return true
      } else {
        return false
      }
    },
    // 未开始和正在处理的才显示处理按钮
    showAction(item) {
      if (this.checkedShow) {
        return false
      } else if (item.handleStatus == 'notStart' || item.handleStatus == 'handling') {
        return true
      } else {
        return false
      }
    },
    // 单个处理
    actions(item) {
      console.log(item,'单个处理')
      this.$router.push({
        path: '/qualityManagement/handlingUnqualified',
        query: { list: JSON.stringify([item])}
      })
    },
    setColor(i, item) {
      if (i == "handleStatusText") {
        let colors = {
          未开始: "#ff9d51",
          正在处理: "#1890ff",
          处理完成: "#00B042",
        };
        return colors[item[i]];
      } else {
        return "";
      }
    },
    cancelType() {
      this.params.handleStatus = "";
      this.checkedAll = false;
      this.selectedList = [];
    },
    comfirmType(v) {
      console.log('vvvvvvvvvv',v);
      this.params.handleStatus = v;
      this.searchQuery();
      console.log(this.params.handleStatus);
    },
    toggleAll(all) {
      this.$refs.checkboxGroup.toggleAll(this.checkedAll);
    },
    toggle(index) {
      this.$refs.checkboxes[index].toggle();
    },
    // 点击右上角更多按钮回调
    clickAction() {
      (this.checkedShow = true), (this.operationTxt = "批量处理");
    },
    changed1(v) {
      this.options1.forEach((item) => {
        if (item.value == v) {
          this.params.handleTypeText = v ? item.text : "";
        }
      });
      this.searchQuery();
    },
    // 选择提交开始时间
    confirmCreatedStartTime(date) {
      this.createEndMinDate = date;
      this.params.applyTimeBegin = moment(date)
        .startOf("day")
        .format("YYYY-MM-DD HH:mm:ss");
      this.params.applyTimeEnd = ""; // 切换开始时间后直接置空结束时间重新选择
      this.createdTimeBeginVisible = false;
      this.createdTimeEndVisible = true;
      this.createdTimeRead = moment(date).format("YYYY-MM-DD");
    },
    // 取消提交开始时间
    cancelCreatedStartTime() {
      this.params.applyTimeBegin = "";
      this.params.applyTimeEnd = "";
      this.createdTimeRead = "";
      this.minDate = new Date();
      this.searchQuery();
      this.createdTimeBeginVisible = false;
    },
    // 选择提交结束时间
    confirmCreatedEndTime(date) {
      this.params.applyTimeEnd = moment(date)
        .endOf("day")
        .format("YYYY-MM-DD HH:mm:ss");
      this.createdTimeEndVisible = false;
      this.createdTimeRead =
        this.createdTimeRead + "~" + moment(date).format("YYYY-MM-DD");
      this.searchQuery();
    },
    // 取消提交结束时间
    cancelCreatedEndTime() {
      this.params.applyTimeBegin = "";
      this.params.applyTimeEnd = "";
      this.createdTimeRead = "";
      this.minDate = new Date();
      this.searchQuery();
      this.createdTimeEndVisible = false;
    },
    onSearch(v) {
      this.keyword = v;
      console.log(this.keyword);
      this.searchQuery();
    },
    onScreen() {
      console.log("筛选");
      this.keyword = this.$refs.topSearch.value;
      this.propsForSon = {
        ...this.params,
        createdTimeRead: this.createdTimeRead,
      };
      this.propsForSon.keyword = this.keyword
      this.showSearchTag = true;
      this.title = "更多筛选";
    },
    resetCategory() {
      this.showSearchTag = false;
    },
    getCategory(p, k) {
      this.params = p;
      this.selectedList = p.handleStatus ? p.handleStatus.split(",") : [];
      this.createdTimeRead = p.createdTimeRead;
      this.keyword = k;
      this.showSearchTag = false;
      console.log(this.params, '不合格品待处理');
      this.$refs.topSearch.value = k;
      this.title = "不合格品待处理";
      this.searchQuery();
    },
    // 获取选择的列表数据
    getCheckedValue(ids, item) {
      this.checkedShow = false
      console.log(ids, item);
      if(item.length == 1){
        this.actions(item[0])
        return
      }
      this.notLeave = false
      let list = item
      list.filter(g => {
        g.num = g.canHandleNum
        g.handleTypeText = ''
      })
      localStorage.setItem('bis_UNQUALIFIEDS', JSON.stringify(list))
      this.$router.push({
        path: '/qualityManagement/handlingUnqualifieds'
      })
    },
    // 列表动态按钮
    asyncBtn(item) {
      if (item.handleStatus != "finish") {
        return "处理";
      } else {
        return "";
      }
    },
    //列表点击事件
    handleList(id, item, type) {
      console.log(id, item, type, "id:列表id,item:列表对象,type:事件名");
    },
    // 加载列表
    getList() {
      // 传1代表从第一条数据开始
      this.$refs.pageList.onLoad(1);
    },
    // 搜索
    searchQuery() {
      // 搜索条件
      let queryParam = {
        ...this.params,
      };
      queryParam.keyword = this.keyword
      this.$refs.pageList.searchQuery(queryParam);
    },
    // 重置
    searchReset() {
      this.$refs.pageList.searchReset();
    },
  },
};
</script>
<style lang="scss" scoped>
.box-content {
  height: 100vh;
  overflow-y: scroll;
  .serach {
    height: 0.33rem;
    background: #f2f2f6;
    border-radius: 0rem;
    margin-bottom: 0.16rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    line-height: 0.33rem;
    padding: 0.1rem 0.12rem;
    // border: 1px solid red;
    .placeh {
      font-size: 0.16rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #888888;
      line-height: 0.23rem;
    }
    .icon {
      width: 0.15rem;
      height: 0.16rem;
    }
  }
  .serach-content {
    // height: 1.52rem;
    background: #ffffff;
    padding: 0 0.16rem 0.16rem 0.16rem;
    .content {
      display: flex;
      .tapbtn {
        // height: 0.23rem;
        // background: #1890ff;
        background: #f2f2f6;
        border-radius: 0.02rem;
        font-size: 0.16rem;
        font-family: PingFang SC;
        font-weight: 500;
        color: #888888;
        line-height: 0.23rem;
        margin-right: 0.12rem;
        text-align: center;
        padding: 0.04rem 0.28rem;
        cursor: pointer;
      }
      .active {
        color: #ffffff;
        background: #1890ff;
      }
    }
  }
}
.foot-slot {
  display: flex;
  justify-content: space-between;
  font-size: 0.14rem;
  color: #1890ff;
}
.search-bottom {
  height: 0.5rem;
  width: 100%;
  background: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.11rem;
  .btnconfirm {
    width: 1.72rem;
    height: 0.39rem;
    background: #1890ff;
    border-radius: 0rem;
    text-align: center;
    line-height: 0.39rem;
    color: #fff;
  }
  .btncancel {
    width: 1.72rem;
    height: 0.39rem;
    background: #f6f6f6;
    border: 0.01px solid rgba(25, 31, 37, 0.12);
    border-radius: 0rem;
    text-align: center;
    line-height: 0.39rem;
  }
}
.label {
  margin-left: -0.03rem;
  margin-top: -0.1rem;
  span {
    height: 0.16rem;
    background: #f0f6fe;
    color: #1890ff;
    margin-right: 0.1rem;
    padding: 0.03rem 0.08rem;
    font-size: 0.11rem;
    border-radius: 0.03rem;
  }
}
.listBox {
  height: calc(100vh - 1.5rem);
  overflow-y: auto;
}
/deep/.van-nav-bar {
  z-index: 99!important;
}
/deep/ .van-checkbox__icon--checked .van-icon{
  border-radius: 0.02rem !important;
}
/deep/ .van-checkbox__icon .van-icon{
  border-radius: 0.02rem !important;
}
</style>